<template>
  <div class="p-3">
    <!-- 主体 -->
    <div>
      <!-- search -->
      <div class="form">
        <div class="fs-3" @click="router.push('/')">cpu管理</div>
        <div>
          <NForm inline>
            <NFormItem>
              <NInput v-model:value="queryInfo.cpu" placeholder="请输入cpu名称"></NInput>
            </NFormItem>
            <NFormItem>
              <NInput v-model:value="queryInfo.manufacturer" placeholder="请输入厂商名称"></NInput>
            </NFormItem>
            <NFormItem>
              <NSpace>
                <NButton @click="requery" type="info">查询</NButton>
                <NButton @click="reset" type="error">重置</NButton>
                <NButton @click="showAdd" type="primary">添加</NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>
      </div>

      <!-- 表格 -->
      <div>
        <NDataTable :columns="columns" :data="cpuList" :loading="tableLoading"></NDataTable>
      </div>

      <!-- 分页 -->
      <div class="page">
        <NFlex justify="center">
          <NPagination
            v-model:page="queryInfo.pageNumber"
            :page-size="queryInfo.pageSize"
            :item-count="page.total"
            @update-page="queryCpuInfo"
          ></NPagination>
        </NFlex>
      </div>
    </div>

    <!-- 弹框 -->
    <div>
      <!-- 添加 -->
      <div>
        <NModal v-model:show="addVisible" title="添加cpu信息" preset="dialog">
          <div>
            <NForm>
              <NFormItem label="cpu名称">
                <NInput v-model:value="addInfo.cpu"></NInput>
              </NFormItem>
              <NFormItem label="厂商名称">
                <NInput v-model:value="addInfo.manufacturer"></NInput>
              </NFormItem>
              <NFormItem label="cpu简介">
                <NInput v-model:value="addInfo.info"></NInput>
              </NFormItem>
              <NFormItem label="cpu核心数">
                <NInputNumber v-model:value="addInfo.cores" button-placement="both"></NInputNumber>
              </NFormItem>
              <NFormItem label="cpu线程数">
                <NInputNumber
                  v-model:value="addInfo.threads"
                  button-placement="both"
                ></NInputNumber>
              </NFormItem>
              <NFormItem label="cpu频率">
                <NInput v-model:value="addInfo.frequency"></NInput>
              </NFormItem>
              <NFormItem label="cpu最高频率">
                <NInput v-model:value="addInfo.maxFrequency"></NInput>
              </NFormItem>
              <NFormItem label="发布时间">
                <NDatePicker
                  date-format="yyyy-MM-dd"
                  v-model:formatted-value="dateinfo"
                  :is-date-disabled="dateValidate"
                ></NDatePicker>
              </NFormItem>
            </NForm>
          </div>

          <template #action>
            <NSpace justify="end">
              <NButton @click="add" type="primary" :loading="addLoading">确定添加</NButton>
            </NSpace>
          </template>
        </NModal>
      </div>

      <!-- 修改 -->
      <div>
        <NModal v-model:show="modifyVisible" title="修改cpu信息" preset="dialog" type="warning">
          <div>
            <NForm>
              <NFormItem label="cpu名称">
                <NInput v-model:value="modifyInfo.cpu"></NInput>
              </NFormItem>
              <NFormItem label="厂商名称">
                <NInput v-model:value="modifyInfo.manufacturer"></NInput>
              </NFormItem>
              <NFormItem label="cpu简介">
                <NInput v-model:value="modifyInfo.info"></NInput>
              </NFormItem>
              <NFormItem label="cpu核心数">
                <NInputNumber
                  v-model:value="modifyInfo.cores"
                  button-placement="both"
                ></NInputNumber>
              </NFormItem>
              <NFormItem label="cpu线程数">
                <NInputNumber
                  v-model:value="modifyInfo.threads"
                  button-placement="both"
                ></NInputNumber>
              </NFormItem>
              <NFormItem label="cpu频率">
                <NInput v-model:value="modifyInfo.frequency"></NInput>
              </NFormItem>
              <NFormItem label="cpu最高频率">
                <NInput v-model:value="modifyInfo.maxFrequency"></NInput>
              </NFormItem>
              <NFormItem label="发布时间">
                <NDatePicker
                  date-format="yyyy-MM-dd"
                  v-model:formatted-value="dateinfo"
                  :is-date-disabled="dateValidate"
                ></NDatePicker>
              </NFormItem>
            </NForm>
          </div>

          <template #action>
            <NSpace justify="end">
              <NButton @click="modify" type="warning" :loading="modifyLoading">保存</NButton>
            </NSpace>
          </template>
        </NModal>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Api } from '@/types/Api'
import type { BaseDataResult, BaseResult, PageBean, PageVO } from '@/types/BaseResult'
import type { TbCpuInfo } from '@/types/crud'
import { Tools } from '@/types/Tools'
import {
  NSpace,
  useMessage,
  useDialog,
  NDataTable,
  type DataTableColumn,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NFlex,
  NPagination,
  NModal,
  NDatePicker,
  NInputNumber,
} from 'naive-ui'
import { h, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const message = useMessage()
const dialog = useDialog()

//#region 查询

// cpu信息列表
const cpuList = ref([] as Array<TbCpuInfo>)
// 表格加载状态
const tableLoading = ref(false)
const page = ref({ pageNumber: 1, pageSize: 5 } as PageBean)
// 请求的参数
const queryInfo = ref({
  cpu: '',
  manufacturer: '',
  pageNumber: page.value.pageNumber,
  pageSize: page.value.pageSize,
})

// 查询cpu信息
const queryCpuInfo = () => {
  tableLoading.value = true
  Api.get('/crud/cpuinfo', queryInfo.value, (data: BaseDataResult<PageVO<TbCpuInfo>>) => {
    tableLoading.value = false
    if (data.success) {
      cpuList.value = data.data.list
      page.value = data.data.pageBean
      return
    }
    message.error(data.message)
  })
}
onMounted(() => {
  queryCpuInfo()
})

// 重查（有查询条件后）
const requery = () => {
  queryInfo.value.pageNumber = 1
  queryCpuInfo()
}

// 重置
const reset = () => {
  queryInfo.value.manufacturer = ''
  queryInfo.value.cpu = ''
  requery()
}

//#endregion

//#region 添加
const addInfo = ref({} as TbCpuInfo)
const addLoading = ref(false)
const addVisible = ref(false)
const dateinfo = ref(Tools.formatDate(new Date(), 'yyyy-MM-dd'))

// 时间校验，时间选择器限定，不能选未来的时间
const dateValidate = (ts: number) => {
  return new Date().getTime() <= ts
}

const showAdd = () => {
  tableLoading.value = true
  addInfo.value.cpu = ''
  addInfo.value.manufacturer = ''
  addInfo.value.info = ''
  addInfo.value.cores = 0
  addInfo.value.threads = 0
  addInfo.value.frequency = ''
  addInfo.value.maxFrequency = ''
  addInfo.value.releaseDate = Tools.formatDate(new Date(), 'yyyy-MM-dd')
  tableLoading.value = false
  addVisible.value = true
}

const add = () => {
  addLoading.value = true
  addInfo.value.releaseDate = dateinfo.value
  Api.post('/crud/cpuinfo', addInfo.value, (data: BaseResult) => {
    addLoading.value = false
    if (data.success) {
      requery()
      addVisible.value = false
      message.success('添加成功')
      return
    }
    message.error(data.message)
  })
}
//#endregion

//#region 修改
const modifyInfo = ref({} as TbCpuInfo)
const modifyVisible = ref(false)
const modifyLoading = ref(false)

const showModify = (info: TbCpuInfo) => {
  tableLoading.value = true
  modifyInfo.value = Tools.concatJson(info) as TbCpuInfo
  dateinfo.value = Tools.formatDate(info.releaseDate as number, 'yyyy-MM-dd')
  tableLoading.value = false
  modifyVisible.value = true
}

const modify = () => {
  modifyLoading.value = true
  modifyInfo.value.releaseDate = dateinfo.value
  Api.put(`/crud/cpuinfo`, modifyInfo.value, (data: BaseResult) => {
    modifyLoading.value = false
    if (data.success) {
      modifyVisible.value = false
      message.success('修改成功')
      return
    }
    message.error(data.message)
  })
}

//#endregion

//#region 删除
const showdelete = (info: TbCpuInfo) => {
  dialog.error({
    title: '警告',
    content: `确定删除${info.cpu}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      tableLoading.value = true
      Api.delete(`/crud/cpuinfo/${info.id}`, {}, (data: BaseResult) => {
        tableLoading.value = false
        if (data.success) {
          message.success('删除成功')
          requery()
          return
        }
        message.error(data.message)
      })
    },
  })
}
//#endregion

// table数据处理
const columns = [
  { title: '型号', key: 'cpu' },
  { title: '厂商', key: 'manufacturer' },
  { title: '简介', key: 'info' },
  { title: '核心数', key: 'cores' },
  { title: '线程数', key: 'threads' },
  { title: '频率', key: 'frequency' },
  { title: '最高频率', key: 'maxFrequency' },
  {
    title: '发布日期',
    key: 'releaseDate',
    render: (row) => {
      return h('span', {}, Tools.formatDate(row.releaseDate as number, 'yyyy-MM-dd'))
    },
  },
  {
    title: '操作',
    key: 'action',
    render: (row) => {
      return h(NSpace, {}, [
        h(
          NButton,
          {
            size: 'small',
            type: 'warning',
            onClick: () => {
              showModify(row)
            },
          },
          '修改',
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => {
              showdelete(row)
            },
          },
          '删除',
        ),
      ])
    },
  },
] as Array<DataTableColumn<TbCpuInfo>>
</script>

<style scoped lang="scss"></style>
